<?php
/**
 * PhalApi_Logger_File 文件日记纪录类
 *
 * - 将日记写入文件，文件目录可以自定义
 *
 * <br>使用示例：<br>
 * ```
 *      //目录为./Runtime，且保存全部类型的日记
 *      $logger = new PhalApi_Logger_File('./Runtime',
 *            PhalApi_Logger::LOG_LEVEL_DEBUG | PhalApi_Logger::LOG_LEVEL_INFO | PhalApi_Logger::LOG_LEVEL_ERROR);
 *
 *      //日记会保存在在./Runtime/debug_log/目录下
 *      $logger->debug('this is bebug test');
 * ```
 *
 * @package     PhalApi\Logger
 * @license     http://www.phalapi.net/license GPL 协议
 * @link        http://www.phalapi.net/
 * @author      dogstar <chanzonghuang@gmail.com> 2014-10-02
 */

class PhalApi_Logger_File extends PhalApi_Logger
{
	
	/** 外部传参 **/
	protected $logFolder;
	protected $dateFormat;
	
	/** 内部状态 **/
	protected $fileDate;
	protected $logFile;
	protected $nodejsFile;
	
	public function __construct($logFolder, $level, $dateFormat = 'Y-m-d H:i:s')
	{
		$this->logFolder  = $logFolder;
		$this->dateFormat = $dateFormat;
		
		parent::__construct($level);
		
		$this->init();
	}
	
	// 保存日志
	public function saveText($info, $msg = '')
	{
		$file = API_ROOT.'/../log/phalapi/text_'.date('Y-m-d').'.log';
		$msg  = date('y-m-d H:i:s').' '.$msg.' '.(is_array($info) ? json_encode($info, JSON_UNESCAPED_UNICODE) : $info);
		file_put_contents($file, $msg."\r\n", FILE_APPEND);
	}
	
	// 检查日志文件以及目录
	protected function init()
	{
		// 跨天时新建日记文件
		$curFileDate = date('Ymd', time());
		if($this->fileDate == $curFileDate){
			return;
		}
		$this->fileDate = $curFileDate;
		
		$this->filePath('log');
		$this->filePath('nodejs');
		
	}
	
	// 自定义 写入日志
	public function type($type, $msg, $data = [])
	{
		$this->log($type, $msg, $data);
	}
	
	// 写入日志
	public function log($type, $msg, $data)
	{
		// 文件
		//$file = $type == 'nodejs' ? $this->nodejsFile : $this->logFile;
		if($type == 'nodejs'){
			$file    = $this->nodejsFile;
			$_data   = json_decode($data['data'], true);
			$_roomId = $_data['msg'][0]['roomnum'] ?? 0;
			if($_roomId){
				$file = dirname($file).DIRECTORY_SEPARATOR.$_roomId.'_'.$this->fileDate.'.log';
			}
		} else{
			$file = $this->logFile;
		}
		
		
		$this->init();
		$this->checkLogSize($file);
		
		// 组合数据
		$msgArr   = array();
		$msgArr[] = date($this->dateFormat, time());
		$msgArr[] = strtoupper($type);
		$msgArr[] = str_replace(PHP_EOL, '\n', $msg);
		if($data !== null){
			$msgArr[] = is_array($data) ? json_encode($data, JSON_UNESCAPED_UNICODE) : $data;
		}
		
		$content = implode('|', $msgArr).PHP_EOL;
		if('response' == $type){
			$content .= PHP_EOL;
		}
		
		file_put_contents($file, $content, FILE_APPEND);
	}
	
	// 检查日志文件大小并自动生成备份文件
	protected function checkLogSize(string $logFile):void
	{
		if(is_file($logFile) && floor(2 * 1024 * 1024) <= filesize($logFile)){
			rename($logFile, dirname($logFile).DIRECTORY_SEPARATOR.time().'-'.basename($logFile));
		}
	}
	
	// 文件以及文件路径
	protected function filePath($type = 'log')
	{
		// 每月一个目录
		$folder = $this->logFolder.DIRECTORY_SEPARATOR.$type.DIRECTORY_SEPARATOR.substr($this->fileDate, 0, -2);
		if(!file_exists($folder)){
			mkdir($folder.'/', 0777, true);
		}
		
		// 获取文件
		$logFile = $folder.DIRECTORY_SEPARATOR.$this->fileDate.'.log';
		if($type == 'nodejs'){
			$this->nodejsFile = $logFile;
		} else{
			$this->logFile = $logFile;
		}
		
		// 创建文件
		if(!file_exists($logFile)){
			// 当没有权限时，touch会抛出(Permission denied)异常
			@touch($logFile);
			// touch失败时，chmod会抛出(No such file or directory)异常
			if(file_exists($logFile)){
				chmod($logFile, 0777);
			}
		}
	}
	
}
